<?php 

Class appController extends Controller
{
	
	
    public function _initialize()
	{ 
		
		
		if (isset($_GET['code'])&&hy_check($_GET['code'],'un')=='#@_error')
		{
			hy_404();
		}
		
		/*开启手机功能*/
		//$cfg=Model('app')->get_cfg();
		$is_wap=C('wap_support');
		
		if($is_wap==1)
		{
			$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
			
			$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile)/i";
			
			if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
			{
				$Loaction = '?g=mobile&a=index&m=index';
			
				if (!empty($Loaction))
				{
					header("Location: $Loaction\n");
			
					
				}
			
			}
		}	
		/*模板*/

		//配置会员信息
		
        //注册函数 registerPlugin
//        $this->registerPlugin("function","func",array('appController','tpl_model'));
    //    $this->assign_global();//栏目
      
	}
	
	// 注册一下
	
	public static function tpl_model($arg)
	{
		if(!empty($arg['model'])&&!empty($arg['action']))
			$item=Model($arg['model'])->$arg['action']($arg);
		//Ctrl('app')->assign($arg['item'], $item);
		
		return $item;
	}
	public function assign_global($config=array())
	{
		$cfg=Model('app')->get_cfg();
		//var_dump($cfg);
// 		echo C('appid');
		//$user=Model('user')->get_user(session('user_id'));
		
		if(isset($config['c']))
		{
			foreach($config['c'] as $k=>$v)
			{
				if(isset($cfg[$k]))
				{
					$cfg[$k]=$v;
						
				}
			}
		}
		C($cfg);
		
		C('lang',DEFAULT_LANG);
		//样式路径
		
		
		
		$path=SUBDIR."/Mobile/Webroot/".C('home_tpl').'/';	
		$this->set_tpl_dir('',C('home_tpl'));
		C('hy_path',$path);
		
		
	
		//配置
		
		$this -> assign('_GET',$_GET);
		$this -> assign('_C',C());
		$this -> assign('_L',Lang());
	}
	/**
	 *  是否已登录
	 * @access public
	 * @return void
	 */
	public function check_member()
	{
		
		if(!isset($_SESSION['wxid']))
		{
			$m = Model('app');
			$app = $m->get_app();
			
				$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			if(!isset($_GET['code']))
			{
				$url = $this->parseurl($url);
				header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app['appid'].'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
				exit();
			}
			else
			{
				
				$access_token = $m->getAccessToken();
				$weiXinObj = new weixinController();
				$code = $_GET['code'];
				$arr = $weiXinObj->getUserByCode($app['appid'], $app['appsecret'], $code);
				$check_openid = $m->get_count_openid($arr['openid']);
				if($check_openid == 0)
				{
					$str = $weiXinObj->getUserInfo($arr['openid'], $arr['access_token']);
					$info['openid'] = $str['openid'];
					$info['nickname'] = $str['nickname'];
					$info['sex'] = $str['sex'];
					$info['headimgurl'] = $str['headimgurl'];
					$wxid =$m->insert_into_wxuser($info);
					if(!$wxid)
					{
						echo "System Error! Please wait for a while!";
					}
				}
				else
				{
					$wxid = $m->get_wxid($arr['openid']);
				}
				$_SESSION['wxid'] = $wxid;
				header('Location:'.$url);
				exit();
			}
		}
	}
	
	public function parseurl($url=""){
		$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
		return $url;
	}
	
   
	public function get_ad($code)
	{
		$ad=Model('app')->get_ad($code);
		return $ad;
	}
	public function get_user_info()
	{
	    unset($_SESSION['YAOID']);
	    if(!isset($_SESSION['YAOID'])){
	        $code = $_GET['code'];
	        $m = Model('app');
	        $path = ROOT_PATH."Admin/Config/yaotv.json";
	        $data = json_decode(file_get_contents($path), true);
	        $app['appid'] = $data['yaoappid'];
	        $access_token = $m->getYaoAccessToken();
	        // 			$weiXinObj = new weixinController();
	        $arr = $this->return_user_info($app['appid'], $access_token, $code);
	        if(!isset($arr['openid'])){
	            $res['error'] = 1;
	            $res['content'] = "请重新登录";
	            unset($_SESSION['YAOID']);
	            die($_REQUEST['callback']."(".json_encode($res).")");
	        }
	        $check_openid = $m->get_count_openid($arr['openid']);
	        if($check_openid == 0)
	        {
	            $info['openid'] = $arr['openid'];
	            $info['nickname'] = $arr['nickname'];
	            $info['sex'] = $arr['sex'];
	            $info['headimgurl'] = $arr['headimgurl']."/64";
	            // 				$info['integral'] = 100;
	            $wxid =$m->insert_into_wxuser($info);
	            if(!$wxid)
	            {
	                echo "System Error! Please wait for a while!";
	            }
	        }
	        else
	        {
	            $wxid = $m->get_wxid($arr['openid']);
	        }
	        $_SESSION['YAOID'] = $wxid;
	        return $wxid;
	    }else{
	        return $_SESSION['YAOID'];
	    }
	}
	
	public function return_user_info($appid,$access_token,$code){
	    $url = "https://api.weixin.qq.com/yaotv/user/userinfo?appid=".$appid."&access_token=".$access_token."&code=".$code;
	    $json = file_get_contents($url);//获取微信用户基本信息
	    $arr = json_decode($json,true);
	    if($arr["openid"]){
	        $this->write_log($arr['openid'], $code);
	    }else{
	        $this->write_error($arr, $url);
	    }
	    return $arr;
	}
	
	public function write_log($openid,$code){
	    $file = ROOT_PATH."Qiaqia/Log/tv_err.log";
	    $content = "wxid：".date("Y-m-d H:i:s").": code:".$code." openid:".$openid.PHP_EOL;
	    $f  = file_put_contents($file, $content,FILE_APPEND);
	}
	
	public function write_error($error,$url)
	{
	    $file = ROOT_PATH."Qiaqia/Log/tv_errmsg.log";
	    $content = "error：".date("Y-m-d H:i:s").": url:".$url.PHP_EOL." errMsg:{".PHP_EOL;
	    foreach($error as $k=>$v){
	        $content.=" $k => $v;".PHP_EOL;
	    }
	    $content."}".PHP_EOL;
	    $f  = file_put_contents($file, $content,FILE_APPEND);
	}
	public function check_member2()
	{
	    if(!isset($_SESSION['wxid']))
	    {//此处需要授权
	        $m = Model('app');
	        $app = $m->get_app();
	        //     	    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	        if(isset($_GET['source'])){//判断是否是扫码进入
	            //有表示第一次进入
	            $url = $this->parseurl("http://g4.airefp.com/index.php?g=mobile&m=message&a=test&sncode=".$_GET['code']);
	            header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app['appid'].'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
	            exit();
	        }else{
	            //无表示已经二次进入
	            $access_token = $m->getAccessToken();
	            $weiXinObj = new weixinController();
	            $code = $_GET['code'];
	            $arr = $weiXinObj->getUserByCode($app['appid'], $app['appsecret'], $code);
	            $check_openid = $m->get_count_openid($arr['openid']);
	            if($check_openid == 0)
	            {
	                $str = $weiXinObj->getUserInfo($arr['openid'], $arr['access_token']);
	                $info['openid'] = $str['openid'];
	                $info['nickname'] = $str['nickname'];
	                $info['sex'] = $str['sex'];
	                $info['headimgurl'] = $str['headimgurl'];
	                $wxid =$m->insert_into_wxuser($info);
	                if(!$wxid)
	                {
	                    echo "System Error! Please wait for a while!";
	                    exit();
	                }
	            }
	            else
	            {
	                $wxid = $m->get_wxid($arr['openid']);
	            }
	            $_SESSION['wxid'] = $wxid;
	            header('Location:http://g4.airefp.com/index.php?g=mobile&m=message&a=test&sncode='.$_GET['sncode']);
	            exit();
	        }
	    }
	}
}


